#!/usr/bin/env bash

vagrant_dir=$(cd "$(dirname "$0")"; pwd)
magento_ce_dir="${vagrant_dir}/magento2ce"
magento_ee_dir="${magento_ce_dir}/magento2ee"
host_os=$(bash "${vagrant_dir}/scripts/host/get_host_os.sh")
php_executable=$(bash "${vagrant_dir}/scripts/host/get_path_to_php.sh")

# Enable trace printing and exit on the first error
set -ex

if [ ! -f ${magento_ee_dir}/app/etc/aliases_to_classes_map.json ]; then
    echo "EE codebase is not available"
    exit 0
fi

if [ -f ${magento_ce_dir}/app/etc/aliases_to_classes_map.json ]; then
    echo "Already switched to EE"
    exit 0
fi

${php_executable} -f ${magento_ee_dir}/dev/tools/build-ee.php -- --command=link --ee-source="${magento_ee_dir}" --ce-source="${magento_ce_dir}"

cp ${magento_ee_dir}/composer.json ${magento_ce_dir}/composer.json
cp ${magento_ee_dir}/composer.lock ${magento_ce_dir}/composer.lock

if [[ ${host_os} == "Windows" || $(bash "${vagrant_dir}/scripts/get_config_value.sh" "guest_use_nfs") == 0 ]]; then
    # Prevent issues on Windows with incorrect symlinks to files
    if [ -f ${magento_ee_dir}/app/etc/aliases_to_classes_map.json ]; then
        rm ${magento_ce_dir}/app/etc/aliases_to_classes_map.json
        cp ${magento_ee_dir}/app/etc/aliases_to_classes_map.json ${magento_ce_dir}/app/etc/aliases_to_classes_map.json
    fi
    if [ -f ${magento_ee_dir}/app/etc/enterprise/di.xml ]; then
        rm ${magento_ce_dir}/app/etc/enterprise/di.xml
        cp ${magento_ee_dir}/app/etc/enterprise/di.xml ${magento_ce_dir}/app/etc/enterprise/di.xml
    fi
fi

bash "${vagrant_dir}/m-clear-cache"
bash -c "${vagrant_dir}/m-composer install"
bash "${vagrant_dir}/m-reinstall"